import pandas as pd
from sqlalchemy import create_engine
from utils.config import get_config


def comments_database():
    """
    将评论数据写入数据库
    """
    # 读取CSV文件
    df = pd.read_csv(f'../../data_csv/comment/merged_comments.csv', header=0)
    df['product_id'] = df['product_id'].astype(str)

    # 添加新列comment_id，其值为当前的索引
    df.insert(0, 'comment_id', df.index)

    config = get_config('../../server_config.ini')

    # 连接到PostgreSQL数据库
    engine = create_engine('postgresql://' + config['user'] + ':' + config['password'] + '@'
                           + config['host'] + ':' + config['port'] + '/' + config['database'])

    # 确保comment_id列被设置为主键并在写入数据库时不包含索引列
    df.to_sql('comments', engine, if_exists='append', index=False, chunksize=10000)
